//
//  XGLoginViewController.swift
//  TodayNews
//
//  Created by monkey on 2020/2/8.
//  Copyright © 2020 itcast. All rights reserved.
//

import UIKit
import MBProgressHUD

/// 切换根控制器通知
let kSwitchKeyWindowRootViewControllerNotification: Notification.Name = Notification.Name(rawValue: "kSwitchKeyWindowRootViewControllerNotification")

class XGLoginViewController: UIViewController
{
    // MARK: - 控制器生命周期方法
    
    override func loadView()
    {
        super.loadView()
        
        setUpUI()
    }
    
    override func viewDidLoad()
    {
        super.viewDidLoad()
        
        navigationItem.title = "登录"
        
        NotificationCenter.default.addObserver(self, selector: #selector(textDidChangeNotification), name: UITextField.textDidChangeNotification, object: nil)
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?)
    {
        view.endEditing(true)
    }
    
    // MARK: - 私有属性
    
    /// 手机号
    private lazy var phoneNumberTextField: UITextField = {
        let textField = UITextField()
        textField.placeholder = "请输入手机号"
        textField.clearButtonMode = .whileEditing
        textField.borderStyle = .roundedRect
        textField.font = UIFont.systemFont(ofSize: 17)
        textField.keyboardType = .phonePad
        return textField
    }()
    /// 密码
    private lazy var passwordTextField: UITextField = {
        let textField = UITextField()
        textField.placeholder = "请输入密码"
        textField.clearButtonMode = .whileEditing
        textField.borderStyle = .roundedRect
        textField.font = UIFont.systemFont(ofSize: 17)
        textField.isSecureTextEntry = true
        return textField
    }()
    /// 登录按钮
    private lazy var loginButton: UIButton = { [weak self] in
        let button = UIButton(title: "进入头条", fontSize: 20, normalColor: UIColor.white, highlightedColor: UIColor.white, target: self, action: #selector(loginAction))
        button.setBackgroundImage(UIColor.colorWithHexString(hexadecimal: "#FF6A6A").toImage(), for: .normal)
        button.setBackgroundImage(UIColor.colorWithHexString(hexadecimal: "#FFAEB9").toImage(), for: .disabled)
        button.isEnabled = false
        button.layer.cornerRadius = 20
        button.layer.masksToBounds = true
        return button
        }()
    /// 注册按钮
    private lazy var registerButton: UIButton = {
        let button = UIButton(title: "还没有账号?点击注册", fontSize: 15, normalColor: UIColor.lightGray, target: self, action: #selector(registerAction))
        return button
    }()
    /// 重置密码按钮
    private lazy var resetPasswordButton: UIButton = {
        let button = UIButton(title: "忘记密码?点击重置", fontSize: 15, normalColor: UIColor.lightGray, target: self, action: #selector(resetPasswordAction))
        return button
    }()
    private let viewModel = XGLoginViewModel()
}

// MARK: - 私有扩展

private extension XGLoginViewController
{
    /// 登录事件
    @objc func loginAction() -> Void
    {
        view.endEditing(true)
        
        MBProgressHUD.showProgressHUD(text: "登录中...")
        viewModel.login(userName: phoneNumberTextField.text!, password: passwordTextField.text!) { (isSuccess, errorMessage) in
            if isSuccess {
                MBProgressHUD.showSuccessTips(text: "登录成功!")
                // 延迟切换控制器
                DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 2) {
                    MBProgressHUD.hideHUD()
                    NotificationCenter.default.post(name: kSwitchKeyWindowRootViewControllerNotification, object: XGMainViewController.self, userInfo: nil)
                }
            } else {
                MBProgressHUD.showErrorTips(text: errorMessage!)
            }
        }
    }
    
    /// 注册账号事件
    @objc func registerAction() -> Void
    {
        view.endEditing(true)
        let registerViewController = XGRegisterViewController()
        navigationController?.pushViewController(registerViewController, animated: true)
    }
    
    /// 重置密码
    @objc func resetPasswordAction() -> Void
    {
        view.endEditing(true)
        let viewController = XGResetPasswordViewController()
        navigationController?.pushViewController(viewController, animated: true)
    }
    
    /// textField通知监听方法
    @objc func textDidChangeNotification() -> Void
    {
        loginButton.isEnabled = phoneNumberTextField.hasText && passwordTextField.hasText
    }
    
    /// qq登录
    @objc func qqLoginAction() -> Void
    {
        viewModel.loginIn(platform: .QQ, completion: loginCompletionHandle())
    }
    
    /// 微博登录
    @objc func sinaLoginAction() -> Void
    {
        viewModel.loginIn(platform: .sina, completion: loginCompletionHandle())
    }
    
    /// 微信登录
    @objc func weiChatLoginAction() -> Void
    {
        viewModel.loginIn(platform: .wechatSession, completion: loginCompletionHandle())
    }
    
    /// 登录完成回调
    func loginCompletionHandle() -> (Bool) -> Void
    {
        let block = { (isSuccess: Bool) in
            if isSuccess {
                MBProgressHUD.showSuccessTips(text: "登录成功!")
                // 延迟切换控制器
                DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 2) {
                    MBProgressHUD.hideHUD()
                    NotificationCenter.default.post(name: kSwitchKeyWindowRootViewControllerNotification, object: XGMainViewController.self, userInfo: nil)
                }
            } else {
                MBProgressHUD.showErrorTips(text: "登录失败")
            }
        }
        
        return block
    }
    /// 设置界面
    func setUpUI() -> Void
    {
        view.backgroundColor = UIColor.white
        
        let titleLabel = UILabel(text: "登录你的头条, 精彩永不消失!", textColor: UIColor.darkGray, fontSize: 25, textAlignment: .center)
        view.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { (make) in
            make.top.equalTo(view.snp.topMargin).offset(44)
            make.centerX.equalToSuperview()
        }
        
        view.addSubview(phoneNumberTextField)
        view.addSubview(passwordTextField)
        phoneNumberTextField.snp.makeConstraints { (make) in
            make.top.equalTo(titleLabel.snp.bottom).offset(30)
            make.left.equalToSuperview().offset(30)
            make.right.equalToSuperview().offset(-30)
            make.height.equalTo(44)
        }
        passwordTextField.snp.makeConstraints { (make) in
            make.top.equalTo(phoneNumberTextField.snp.bottom).offset(30)
            make.left.right.height.equalTo(phoneNumberTextField)
            make.height.equalTo(44)
        }
        
        view.addSubview(loginButton)
        view.addSubview(registerButton)
        view.addSubview(resetPasswordButton)
        loginButton.snp.makeConstraints { (make) in
            make.top.equalTo(passwordTextField.snp.bottom).offset(30)
            make.centerX.equalToSuperview()
            make.size.equalTo(CGSize(width: ceil(TodayNews_Screen_Width * 0.6), height: 44))
        }
        registerButton.snp.makeConstraints { (make) in
            make.top.equalTo(loginButton.snp.bottom).offset(30)
            make.centerX.equalTo(loginButton)
        }
        resetPasswordButton.snp.makeConstraints { (make) in
            make.top.equalTo(registerButton.snp.bottom).offset(15)
            make.centerX.equalTo(loginButton)
        }
        
        // 添加登录视图
        let qqButton = UIButton(imageName: "qqicon_login_profile_66x66_", target: self, action: #selector(qqLoginAction))
        let weiChatButton = UIButton(imageName: "weixinicon_login_profile_66x66_", target: self, action: #selector(weiChatLoginAction))
        let sinaButton = UIButton(imageName: "sinaicon_login_profile_66x66_", target: self, action: #selector(sinaLoginAction))
        let loginStackView = UIStackView(arrangedSubviews: [qqButton,weiChatButton,sinaButton])
        loginStackView.distribution = .fillEqually
        loginStackView.spacing = 33
        view.addSubview(loginStackView)
        loginStackView.snp.makeConstraints { (make) in
            make.bottom.equalTo(view.snp_bottomMargin).offset(-44)
            make.centerX.equalToSuperview()
            make.size.equalTo(CGSize(width: 66 * 3 + 33 * 2, height: 66))
        }
    }
}
